package com.bawei.module_mall.ui.goodsshow


import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter

import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.module_mall.R
import com.bawei.module_mall.adapter.GoodsAdapter
import com.bawei.module_mall.databinding.FragmentGoodsRecommendBinding
import com.bawei.module_mall.http.intent.ShopIntent
import com.bawei.module_mall.http.state.ShopState
import com.bawei.module_mall.http.viewModel.ShopViewModel
import com.bawei.module_mall.model.RequestSearchGoodsModel
import com.bawei.module_mall.model.SearchGoodsModelItem
import com.blankj.utilcode.util.ToastUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.launch


class GoodsRecommendFragment : BaseMVIFragment() {
    private val binding: FragmentGoodsRecommendBinding by lazy {
        FragmentGoodsRecommendBinding.inflate(layoutInflater)
    }

    private lateinit var viewModel: ShopViewModel

    private var currentAddGoodsId: Int = 0

    private var emptyView: View? = null

    private fun showEmptyLayout() {
        // 确保只添加一次空布局
        if (emptyView == null) {
            emptyView = layoutInflater.inflate(
                R.layout.layout_search_empty,
                binding.root as ViewGroup,
                false
            )
            (binding.root as ViewGroup).addView(emptyView)
        }
        binding.rvRecommend.visibility = View.GONE
        emptyView?.visibility = View.VISIBLE
    }

    private val goodsAdapter: GoodsAdapter by lazy {
        GoodsAdapter(
            onItemClick = { item ->
                if (viewModel.detailIdSet.contains(item.id.toString())) {
                    ARouter.getInstance().build(Router.Ui.SHOP_DETAIL_ACTIVITY)
                        .withInt("shopId", item.id.toInt()).navigation()
                } else {
                    showEmptyLayout()
                }
            },
            showAddButton = true,
            onAddToShowcase = { item ->
                lifecycleScope.launch {
                    currentAddGoodsId = item.id.toInt()
                    viewModel.intents.send(ShopIntent.CheckGoods(currentAddGoodsId))
                }
            }
        )
    }

    // 分页相关变量
    private var currentPage = 1
    private var isLoading = false
    private val pageSize = 4

    // 数据更新回调
    var onDataUpdated: (() -> Unit)? = null

    private var lastSortType: String = ""
    private var lastPriceDesc: Boolean = true

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[ShopViewModel::class.java]
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun initView() {
        binding.rvRecommend.layoutManager = GridLayoutManager(requireActivity(), 2)



        binding.rvRecommend.adapter = goodsAdapter

        // 设置嵌套滚动行为，支持与AppBarLayout的协调滚动
        binding.rvRecommend.isNestedScrollingEnabled = true

        // 确保RecyclerView能够正确与AppBarLayout协调滚动
        binding.rvRecommend.setHasFixedSize(true)

        binding.srl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshData()
                binding.srl.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                loadMoreData()
                binding.srl.finishLoadMore()
            }

        })

    }

    override fun lazyLoad() {
        // 重置分页状态
        currentPage = 1
        isLoading = false

        // 推荐商品参数可根据实际业务调整
        val body = RequestSearchGoodsModel(
            keyWord = "",
            limit = pageSize,
            maxMoney = 0,
            minMoney = 0,
            sort = "",
            sortKey = "",
            start = currentPage
        )

        lifecycleScope.launchWhenStarted {
            viewModel.intents.send(ShopIntent.SearchGoods(body))

            // 初始化时拉取所有有详情的商品ID
            viewModel.fetchDetailIds()
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            viewModel.state.collect {
                Log.d("GoodsRecommendFragment", "收到状态: $it")
                when (it) {
                    is ShopState.SearchGoods -> {
                        Log.d("GoodsRecommendFragment", "推荐商品数量=${it.goodsList.size}")
                        val goodsList = it.goodsList
                        if (goodsList.isNullOrEmpty()) {
                            Log.d("GoodsRecommendFragment", "商品列表为空，隐藏RecyclerView")
                            binding.rvRecommend.visibility = View.GONE
                            showEmptyState()
                        } else {
                            Log.d("GoodsRecommendFragment", "显示商品列表，数量: ${goodsList.size}")
                            binding.rvRecommend.visibility = View.VISIBLE

                            if (currentPage == 1) {
                                // 第一页数据，直接替换
                                goodsAdapter.submitList(goodsList)
                            } else {
                                // 加载更多数据，添加到现有列表
                                val currentList = goodsAdapter.getCurrentList().toMutableList()
                                currentList.addAll(goodsList)
                                goodsAdapter.submitList(currentList)
                            }

                            // 通知Activity更新tab数量
                            onDataUpdated?.invoke()
                            Log.d("GoodsRecommendFragment", "数据更新完成，通知Activity更新tab数量")

                        }
                    }

                    is ShopState.CheckGoods -> {
                        if (it.data) {
                            ToastUtils.showLong("商品已加入橱窗，无需重复添加")
                        } else {
                            // 这里需要记录当前要添加的商品id
                            // 推荐用一个变量保存
                            viewModel.intents.send(ShopIntent.ToggleGoods(currentAddGoodsId))
                        }
                    }

                    is ShopState.ToggleGoods -> {
                        if (it.data) {
                            ToastUtils.showLong("添加成功")
                            refreshData()
                        } else {
                            ToastUtils.showLong("添加失败，请重试")
                        }
                    }

                    is ShopState.Loading -> {
                        Log.d("GoodsRecommendFragment", "加载中...")
                        if (currentPage == 1) {
                            binding.rvRecommend.visibility = View.GONE
                        }
                        isLoading = true
                    }

                    is ShopState.Error -> {
                        Log.e("GoodsRecommendFragment", "错误: ${it.error}")
                        isLoading = false

                        if (currentPage == 1) {
                            binding.rvRecommend.visibility = View.GONE
                            showErrorState(it.error)
                        } else {
                            ToastUtils.showLong("加载失败：${it.error}")
                        }
                    }

                    else -> {
                        Log.d("GoodsRecommendFragment", "其他状态: $it")
                    }
                }
            }
        }
    }

    // 新增：刷新推荐商品列表
    fun refreshData() {
        // 重置分页状态
        currentPage = 1
        isLoading = false

        val body = RequestSearchGoodsModel(
            keyWord = "",
            limit = pageSize,
            maxMoney = 0,
            minMoney = 0,
            sort = "",
            sortKey = "",
            start = currentPage
        )

        lifecycleScope.launch {
            viewModel.intents.send(ShopIntent.SearchGoods(body))
        }
    }

    // 加载更多数据
    private fun loadMoreData() {
        currentPage++
        isLoading = true

        val body = RequestSearchGoodsModel(
            keyWord = "",
            limit = pageSize,
            maxMoney = 0,
            minMoney = 0,
            sort = "",
            sortKey = "",
            start = currentPage
        )

        lifecycleScope.launch {
            viewModel.intents.send(ShopIntent.SearchGoods(body))
        }
    }

    // 显示空状态
    private fun showEmptyState() {
        // 可以在这里显示空状态UI
        ToastUtils.showLong("暂无推荐商品")
    }

    // 显示错误状态
    private fun showErrorState(error: String) {
        // 可以在这里显示错误状态UI
        ToastUtils.showLong("加载失败:$error")
    }

    // 获取商品数量
    fun getGoodsCount(): Int {
        return goodsAdapter.getCurrentList().size
    }

    //判断是否已经初始化
    fun isReady(): Boolean = isAdded && view != null && ::viewModel.isInitialized

    fun sortGoods(sortType: String, priceDesc: Boolean) {
        lastSortType = sortType
        lastPriceDesc = priceDesc
        val list = goodsAdapter.getCurrentList().toMutableList()
        val sorted = applyCurrentSort(list)
        goodsAdapter.submitList(sorted)
    }

    private fun applyCurrentSort(list: List<SearchGoodsModelItem>): List<SearchGoodsModelItem> {
        return when (lastSortType) {
            "soldNum" -> list.sortedByDescending { it.soldNum }
            "createTime" -> list.sortedByDescending { it.createTime } // 如有需要可转为Long排序
            "price" -> if (lastPriceDesc) {
                list.sortedByDescending { it.marketPriceFee }
            } else {
                list.sortedBy { it.marketPriceFee }
            }

            else -> list
        }
    }

}

